import Taro from '@tarojs/taro'

// 类型定义
interface MapApp {
  name: string
  icon: string
  scheme?: string
  url?: string
  action?: 'system'
}

interface ShopLocation {
  latitude: number
  longitude: number
  name: string
  address: string
}

class MapService {
  // 获取地图应用列表
  static getMapApps(latitude: number, longitude: number, name: string, address: string): MapApp[] {
    const mapApps: MapApp[] = []

    // 高德地图
    mapApps.push({
      name: '高德地图',
      icon: 'amap',
      scheme: `androidamap://viewMap?sourceApplication=myapp&poiname=${encodeURIComponent(name)}&lat=${latitude}&lon=${longitude}&dev=0`,
      url: `https://uri.amap.com/marker?position=${longitude},${latitude}&name=${encodeURIComponent(name)}&src=myapp`
    })

    // 百度地图
    mapApps.push({
      name: '百度地图',
      icon: 'baidu',
      scheme: `baidumap://map/marker?location=${latitude},${longitude}&title=${encodeURIComponent(name)}&content=${encodeURIComponent(address)}&src=myapp`,
      url: `https://api.map.baidu.com/marker?location=${latitude},${longitude}&title=${encodeURIComponent(name)}&content=${encodeURIComponent(address)}&output=html&src=myapp`
    })

    // 腾讯地图
    mapApps.push({
      name: '腾讯地图',
      icon: 'tencent',
      scheme: `qqmap://map/marker?marker=coord:${latitude},${longitude};title:${encodeURIComponent(name)};addr:${encodeURIComponent(address)}&referer=myapp`,
      url: `https://apis.map.qq.com/uri/v1/marker?marker=coord:${latitude},${longitude};title:${encodeURIComponent(name)};addr:${encodeURIComponent(address)}&referer=myapp`
    })

    // 系统地图
    mapApps.push({
      name: '系统地图',
      icon: 'system',
      action: 'system'
    })

    return mapApps
  }

  // 显示地图选择弹窗
  static async showMapSelector(latitude: number, longitude: number, name: string, address: string): Promise<void> {
    const mapApps = this.getMapApps(latitude, longitude, name, address)

    const mapNames = mapApps.map(app => app.name)

    try {
      const { tapIndex } = await Taro.showActionSheet({
        itemList: mapNames,
        alertText: '选择地图应用'
      })

      const selectedApp = mapApps[tapIndex]
      await this.openSelectedMap(selectedApp, latitude, longitude, name, address)

    } catch (error) {
      const err = error as TaroGeneral.CallbackResult
      if (err.errMsg !== 'showActionSheet:fail cancel') {
        console.error('选择地图失败:', error)
        await Taro.showToast({
          title: '选择失败',
          icon: 'none'
        })
      }
    }
  }

  // 打开选中的地图应用
  static async openSelectedMap(app: MapApp, latitude: number, longitude: number, name: string, address: string): Promise<void> {
    try {
      if (app.action === 'system') {
        // 打开系统地图
        await Taro.openLocation({
          latitude: latitude,
          longitude: longitude,
          name: name,
          address: address,
          scale: 18
        })
      } else if (app.scheme) {
        // 尝试使用 URL Scheme 打开
        await this.openByScheme(app.scheme, app.url, app.name)
      }
    } catch (error) {
      console.error(`打开${app.name}失败:`, error)
      await Taro.showToast({
        title: `打开${app.name}失败`,
        icon: 'none'
      })
    }
  }

  // 通过 URL Scheme 打开地图应用
  static async openByScheme(scheme: string, webUrl: string = '', appName: string): Promise<void> {
    try {
      // 在 H5 环境中直接跳转
      if (process.env.TARO_ENV === 'h5') {
        window.location.href = scheme
        return
      }

      // 在小程序环境中尝试跳转
      await Taro.navigateTo({
        url: `/pages/webview/webview?url=${encodeURIComponent(scheme)}`
      })
    } catch (error) {
      // 如果跳转失败，提示用户
      const { confirm } = await Taro.showModal({
        title: '提示',
        content: `未检测到${appName}，是否使用网页版地图？`,
        confirmText: '确定',
        cancelText: '取消'
      })

      if (confirm && webUrl) {
        // 跳转到网页版地图
        await Taro.navigateTo({
          url: `/pages/webview/webview?url=${encodeURIComponent(webUrl)}`
        })
      }
    }
  }

  // 直接打开系统地图
  static async openSystemMap(location: ShopLocation): Promise<void> {
    try {
      await Taro.openLocation({
        latitude: location.latitude,
        longitude: location.longitude,
        name: location.name,
        address: location.address,
        scale: 18
      })
    } catch (error) {
      console.error('打开系统地图失败:', error)
      throw error
    }
  }

  // 获取当前位置
  static async getCurrentLocation(): Promise<{ latitude: number; longitude: number }> {
    try {
      const { latitude, longitude } = await Taro.getLocation({
        type: 'gcj02'
      })
      return { latitude, longitude }
    } catch (error) {
      console.error('获取位置失败:', error)
      throw error
    }
  }
}

export default MapService
export type { ShopLocation, MapApp }
